<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Shop\Validator;

use Laminas\I18n\Translator\Translator;
use Laminas\Validator\AbstractValidator;
use User\Entity\UserAddress;

class CheckoutAddressValidator extends AbstractValidator
{
    const NOT_SCALAR        = 'notScalar';
    const ADDRESS_NOT_EXISTS= 'addressNotExists';

    protected $messageTemplates = [];

    protected $entityManager;
    protected $userId;

    public function __construct($options = null)
    {
        if(isset($options['entityManager']))    $this->entityManager = $options['entityManager'];
        if(isset($options['userId']))           $this->userId = $options['userId'];

        $trans = new Translator();
        $this->messageTemplates = [
            self::NOT_SCALAR        => $trans->translate("这不是一个标准输入值"),
            self::ADDRESS_NOT_EXISTS=> $trans->translate("您的收货地址不存在，请重新选择")
        ];

        parent::__construct($options);
    }

    public function isValid($value)
    {
        if(!is_scalar($value)) {
            $this->error(self::NOT_SCALAR);
            return false;
        }

        $isValid = true;

        $addressInfo = $this->entityManager->getRepository(UserAddress::class)->findOneBy(['userId' => $this->userId, 'addressId' => $value]);
        if($addressInfo == null) {
            $isValid = false;
            $this->error(self::ADDRESS_NOT_EXISTS);
        }

        return $isValid;
    }
}